import axios from 'axios';
// import schedule from 'vue-schedule'
import router from '../router';
import bus from '../bus';
// import i18n from '../i18n'
import config from '@/config';
import { Loading, Message } from 'element-ui';
import server from '@/config.js';
const queryString = require('query-string');
let loadingInstance;
// axios 配置
//60000
//axios.defaults.timeout = 600000;
// if(process.env.NODE_ENV === 'production'){
//   const url=window.location.href.split(':')[0]
//   let apiUrl = ''
//   if(url.indexOf('119.145.16.241') !== -1){
//     apiUrl='http://119.145.16.241'
//   }else {
//     apiUrl ='http://172.18.18.28'
//   }
// }
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.baseURL = config.apiServer;
axios.defaults.timeout = 5000;
//POST传参序列化
axios.interceptors.request.use(
  config => {
    loadingInstance && loadingInstance.close();
    loadingInstance = Loading.service({
      target: '.el-container',
      background: 'rgba(255,255,255,0.35)'
    });
    //把token放到参数里面
    // let token = window.localStorage.getItem('token')
    // if (token && config.params) {
    //   config.params.token = token
    // } else {
    //   config.params = { 'token': token }
    // }
    // 把token放到header里面
    if (
      config.method === 'post' ||
      config.method === 'put' ||
      config.method === 'get' ||
      config.method === 'delete'
    ) {
      config.headers.token = window.localStorage.token;
      config.headers.userId = window.localStorage.userId;
    }
    return config;
  },
  error => {
    loadingInstance.close();
    return Promise.reject(error);
  }
);

//返回状态判断
axios.interceptors.response.use(
  res => {
    loadingInstance.close();
    if (!res.data.status) {
      return Promise.reject(res);
    }
    // if (res.data.status != 100) {
    //   return Promise.reject(res);
    // }
    return Promise.resolve(res);
  },
  error => {
    loadingInstance.close();
    if (error.code == 'ECONNABORTED') {
      return Promise.reject(error);
    }
    if (
      error.response.data.status === 120 ||
      error.response.data.status === 130
    ) {
      if (router.currentRoute.fullPath.indexOf('/login') == -1) {
        localStorage.clear();
        router.replace({
          path: 'login',
          query: { redirect: router.currentRoute.fullPath }
        });
        return Promise.reject(error);
      } else {
        return;
      }
    }
    return Promise.reject(error);
  }
);

function fetch(url, params) {
  // alert(JSON.parse(params));
  return new Promise((resolve, reject) => {
    axios
      .post(url, params)
      .then(response => {
        //
        resolve(response.data);
      })
      .catch(error => {
        console.log(error);
        if (error.code == 'ECONNABORTED') {
          Message.error(error.message);
          // reject(error.message);
        } else if (error.status == 200) {
          Message.error(error.message);
          // reject(error.data.message)
        } else if (error.status == 101) {
          Message.error('请求发生错误');
          // reject(error.data.message)
        } else if (error.status == 120) {
          Message.error('请求发生错误');
          // reject(error.data.message)
        } else {
          Message.error(error.response.message);
          // reject(error.response.data.message)
        }
      });
  });
}

function put(url, data) {
  return new Promise((resolve, reject) => {
    axios
      .put(url, data)
      .then(response => {
        resolve(response.data);
      })
      .catch(error => {
        if (error.code == 'ECONNABORTED') {
          Message.error(error.message);
          // reject(error.message);
        } else if (error.status == '122') {
          Message.error('无权限操作');
        } else if (error.status == 200) {
          Message.error(error.data.message);
          // reject(error.data.message)
        } else if (error.status == 101) {
          Message.error('请求发生错误');
          // reject(error.data.message)
        } else {
          Message.error(error.response.data.message);
          // reject(error.response.data.message)
        }
      });
  });
}

function remove(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .delete(url, params)
      .then(response => {
        resolve(response.data);
      })
      .catch(error => {
        if (error.code == 'ECONNABORTED') {
          Message.error(error.message);
          // reject(error.message);
        } else if (error.status == 200) {
          Message.error(error.data.message);
          // reject(error.data.message)
        } else if (error.status == '122') {
          Message.error('无权限操作');
        } else if (error.status == 101) {
          Message.error('请求发生错误');
          // reject(error.data.message)
        } else {
          Message.error(error.response.data.message);
          // reject(error.response.data.message)
        }
      });
  });
}

function get(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, params)
      .then(response => {
        resolve(response.data);
      })
      .catch(error => {
        if (error.code == 'ECONNABORTED') {
          Message.error(error.message);
          // reject(error.message);
        } else if (error.status == 200) {
          Message.error(error.data.message);
          // reject(error.data.message)
        } else if (error.status == '122') {
          Message.error('无权限操作');
        } else if (error.status == 101) {
          Message.error('请求发生错误');
          // reject(error.data.message)
        } else {
          Message.error(error.response.data.message);
          // reject(error.response.data.message)
        }
      });
  });
}

//参数签名
Date.prototype.format = function(fmt) {
  var o = {
    'M+': this.getMonth() + 1, //月份
    'd+': this.getDate(), //日
    'h+': this.getHours(), //小时
    'm+': this.getMinutes(), //分
    's+': this.getSeconds(), //秒
    'q+': Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + '').substr(4 - RegExp.$1.length)
    );
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      );
    }
  }
  return fmt;
};
export const api = {
  setCookie: function(name, value, days) {
    let d = new Date();
    d.setTime(d.getTime() + 24 * 60 * 60 * 1000 * days);
    window.document.cookie =
      name + '=' + value + ';path=/;expires=' + d.toGMTString();
  },
  getCookie: function(name) {
    if (document.cookie.length > 0) {
      let c_start = document.cookie.indexOf(name + '=');
      if (c_start != -1) {
        c_start = c_start + name.length + 1;
        let c_end = document.cookie.indexOf(';', c_start);
        if (c_end == -1) c_end = document.cookie.length;
        return unescape(document.cookie.substring(c_start, c_end));
      }
    }
    return '';
  },
  deleteCookie: function(name) {
    this.setCookie(name, '', -1);
  },
  LocalStorageService: {
    get: function LocalStorageServiceGet(key) {
      var stored = localStorage.getItem(key);
      try {
        stored = JSON.parse(stored);
      } catch (error) {
        stored = null;
      }
      return stored;
    },
    update: function LocalStorageServiceUpdate(key, value) {
      if (value) {
        localStorage.setItem(key, JSON.stringify(value));
      }
    },
    clear: function LocalStorageServiceClear(key) {
      localStorage.removeItem(key);
    }
  },
  Login(parmas) {
    return fetch('/login/login', parmas);
  },

  UserPage(params, query) {
    //用户列表
    return fetch('/user/page?' + queryString.stringify(query), params);
  },
  PackingUnitPage(params, query) {
    return fetch('/hupacking/hulist', query, params);
  },
  UserDetails(userid) {
    //用户详情
    return fetch(`/user/userDetails?cUserId=${userid}`);
  },
  AddUser(params) {
    //添加用户
    return fetch('/user/addUser', params);
  },
  // 三查表内容
  Threepage(params, query) {
    // 三查表列表
    return fetch('/ThreeCheck/page?' + queryString.stringify(query), params);
  },
  // 三查表详情
  ThreeCheckselectlist(query) {
    return put(
      '/ThreeCheck/selectThreeCheckList?',
      queryString.stringify(query)
    );
  },
  // 三查列表新增
  ThreeCheckadd(params) {
    return fetch('/ThreeCheck/addThreeCheck', params);
  },
  contentadd(parmas) {
    //新增检查内容
    return fetch('/content/addContent', parmas);
  },
  contentdelete(query) {
    //删除检查内容
    return put('/content/deleteContent?', queryString.stringify(query));
  },
  contentmodify(params) {
    //修改检查内容
    return put('/content/modify', params);
  },
  contentpage(params, query) {
    //获取检查内容
    return fetch('/content/page?' + queryString.stringify(query), params);
  },
  Depattmentpage(params, query) {
    //获取部门
    return fetch('/department/page?' + queryString.stringify(query), params);
  },
  Depattmentmodify(params) {
    //修改部门
    return put('/department/modify', params);
  },
  Depattmentdelete(query) {
    //删除部门
    return put('/department/deleteDepartment?', queryString.stringify(query));
  },
  Depattmentadd(params) {
    //添加部门
    return fetch('/department/addDepartment', params);
  },
  RolePage(params, query) {
    //获取角色
    return fetch('/role/page?' + queryString.stringify(query), params);
  },
  Trafficpage(params, query) {
    // 交通隐患查询
    return fetch('/TrafficDanger/page?' + queryString.stringify(query), params);
  },
  Traffadd(params) {
    //新增交通
    return fetch('/TrafficDanger/addTrafficDanger', params);
  },
  LogPage(params, query) {
    //日志模块
    return fetch('/log/page?' + queryString.stringify(query), params);
  },
  RoleAdd(params) {
    //添加角色
    return fetch('/role/addRole', params);
  },
  RoleModify(params) {
    //修改角色
    return put('/role/modify', params);
  },
  RoleSeacrch(query, params) {
    return put('/role/selectRoleList?' + queryString.stringify(query), params);
  },
  DeleteRole(query) {
    //删除角色
    return put('/role/deleteRole?', queryString.stringify(query));
  },
  DeleteUser(id) {
    //删除用户
    return put(`/user/deleteUser?cUserId=${id}`);
  },
  UserModifyStatus(query) {
    //修改产品类型状态
    return fetch('/user/updateState?' + queryString.stringify(query));
  },
  RoleModifyStatus(query) {
    //修改产品类型状态
    return put('/role/forbidden?' + queryString.stringify(query), query);
  },
  PermissionPage(data, query) {
    //获取权限
    return fetch('/role/permission?' + queryString.stringify(query), data);
  },
  UserModify(query) {
    //修改用户信息
    return put('/user/modify', query);
  },
  ////////系统管理
  DeleteClient(query) {
    //删除接口
    return put('/client/delete?' + queryString.stringify(query));
  },
  systemPage(params, query) {
    //查询备份
    return fetch('/system/page?' + queryString.stringify(query), params);
  },
  systemRestore(query) {
    ////数据库还原
    return get('/system/restore?' + queryString.stringify(query));
  },
  systemRemove(query) {
    ////删除备份
    return remove('/system/remove/' + query);
  },
  systemBackup() {
    ////数据库备份
    return fetch('/system/backup');
  },
  //根据部门查
  departmentselectId(query) {
    return put(
      '/department/selectDepartmentId?' + queryString.stringify(query)
    );
  },

  // 查询一，二，三级部门
  departmentDetailId(query) {
    return put(
      '/department/selectDepartmentDetailId?' + queryString.stringify(query)
    );
  },

  ////////接口管理
  ClientPage(params, query) {
    //接口列表
    return fetch('/client/page?' + queryString.stringify(query), params);
  },

  AddClient(params, query) {
    //新增接口
    return fetch(
      'client/addOauthClient' + queryString.stringify(query),
      params
    );
  },
  ClientModify(params) {
    //修改接口
    return put('/client/modify', params);
  },
  Hupacking(params, query) {
    return fetch('/hupacking/hulist?' + queryString.stringify(query), params);
  },
  setPackunit(query) {
    return fetch('/hupacking/setPackUnit', query);
  },
  Threepagecontent() {
    return fetch('/ThreeCheck/pageContent');
  },
  ThreecheckList(query) {
    return put(
      '/ThreeCheck/selectThreeCheckList?' + queryString.stringify(query)
    );
  },
  exportData(_url, data) {
    let url = server.apiServer + _url;
    return axios
      .request({
        url,
        data,
        method: 'POST',
        responseType: 'blob',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/octet-stream',
          token: this.getCookie()
        }
      })
      .then(res => {
        return res;
      })
      .catch(error => {
        return error;
      });
  },
  // 通知通报
  sendDope(params) {
    return fetch('/dopeWeb/adminSendDope', params);
  },
  getDopeRoles() {
    return get('/dopeWeb/bindObjectSelect');
  },
  getDopeDeparts() {
    return get('/dopeWeb/findAllDepartment');
  },
  // 流程管控
  findProcess(name, pageSize, currPage) {
    return get(
      `/fiveProcedureWeb/findFiveProcedure?pageSize=${pageSize}&currPage=${currPage}&name=${name}`
    );
  },
  delProcess(id) {
    return put('/fiveProcedureWeb/delFiveEstate?procedureId=' + id);
  },
  addProcess(params) {
    return fetch('/fiveProcedureWeb/addFiveProcedure', params);
  },
  findSupervise(name, pageSize, currentPage) {
    return get(
      `/fourInspectorWeb/findInspectorList?name=${name}&pageSize=${pageSize}&currPage=${currentPage}`
    );
  },
  superviseReceiever() {
    return get('/fourInspectorWeb/bindObjectSelect');
  },
  addSupervise(params) {
    return fetch('/fourInspectorWeb/addFourInspector', params);
  },
  exportProcessExcel(list) {
    return fetch('/exportExcel/exportFiveExcel', list);
  },
  exportSuperviseExcel(list) {
    return fetch('/exportExcel/exportFourExcel', list);
  },
  exportThreeExcel(list) {
    return fetch('/exportExcel/exportThreeExcel', list);
  },
  addThreeTable(params) {
    return fetch('/threeTableWeb/addThreeTable', params);
  },
  getThreeTableGroup(param = '', pageIndex, limit) {
    return get(
      `/threeTableWeb/findThreeMainList?name=${param}&currPage=${pageIndex}&pageSize=${limit}`
    );
  },
  selectThreeDetail(id) {
    return get(`/threeTableWeb/findThreeTaskSelfByID?taskID=${id}`);
  },
  selectThreeContent(id) {
    return get(`/threeTableWeb/findThreeTableById?tableid=${id}`);
  },
  selectSelfDetail(params, pageIndex, limit) {
    return fetch(
      `/threeTableWeb/findThreeTaskSelf?currPage=${pageIndex}&pageSize=${limit}`,
      params
    );
  },
  modifyThree(params) {
    return fetch(`/threeTableWeb/updateThreeTable`, params);
  },
  getRoleTypeList(id) {
    return fetch(`/user/getUsersByRoleId?roleId=${id}`);
  },
  findDope(pageSize, currPage) {
    return get(
      `/dopeWeb/findHistoryDope?pageSize=${pageSize}&currPage=${currPage}`
    );
  },
  findProcessStructure(id) {
    return get(`/fiveProcedureWeb/findProcedureById?procedureId=${id}`);
  },
  findProcessList(id, pageSize, currPage, username) {
    return get(
      `/fiveProcedureWeb/findFiveDetailsList?username=${username}&procedureId=${id}&pageSize=${pageSize}&currPage=${currPage}`
    );
  },
  findProcessDetail(id) {
    return get(`/fiveProcedureWeb/findFiveDetailsById?detailsId=${id}`);
  },
  findSuperviseList(params, pageSize, currPage) {
    return fetch(
      `/fourInspectorWeb/findDetails?pageSize=${pageSize}&currPage=${currPage}`,
      params
    );
  },
  findSuperviseDetail(id) {
    return get(`/fourInspectorWeb/findDetailsById?detailsId=${id}`);
  },
  findSuperviseStructure(id) {
    return get(`/fourInspectorWeb/findFourInspector?inspectorId=${id}`);
  },
  findSuperviseTableList(name, pageSize, currentPage) {
    return get(
      `/fourInspectorWeb/findAllFourInspector?name=${name}&pageSize=${pageSize}&currPage=${currentPage}`
    );
  },
  updateSuperviseStatus(id) {
    return put(`/fourInspectorWeb/updateFourInspectorStatus?inspectorId=${id}`);
  },
  findDepartment(pageSize, currPage, params = {}) {
    return fetch(
      `/department/findDepartment?pageSize=${pageSize}&currPage=${currPage}`,
      params
    );
  },
  addDepartment(parmas) {
    return fetch('/department/addDepartment', parmas);
  },
  updateDepartment(parmas) {
    return fetch('/department/updateDepartment', parmas);
  },
  findDepartmentById(id) {
    return get(`/department/findDepartmentById?id=${id}`);
  },
  findExternal(pageSize, currPage, params) {
    return fetch(
      `/externalWebUser/findExternaUser?pageSize=${pageSize}&currPage=${currPage}`,
      params
    );
  },
  addExternal(params) {
    return fetch(`/externalWebUser/addExternalUser`, params);
  },
  findExternalById(id) {
    return get(`/externalWebUser/findExternaUserById?userid=${id}`);
  },
  updateExternal(params) {
    return fetch(`/externalWebUser/updateExternalUser`, params);
  },
  findDutyOfficer(id) {
    return fetch(`/externalWebUser/findDepartmentUserByID?departmentID=${id}`);
  }
};

export { fetch };
